package org.example.controller.admin;

import com.google.protobuf.Api;
import lombok.extern.slf4j.Slf4j;
import org.example.common.ApiResponse;
import org.example.entity.system.Role;
import org.example.entity.system.User;
import org.example.service.impl.PermissionServiceImpl;
import org.example.service.impl.RoleServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * @Description
 * @Author 魏锴
 * @Date 2024/1/14
 */
@Slf4j
@Controller
@ResponseBody
@RequestMapping("/admin/role")
public class roleController {
    @Autowired
    RoleServiceImpl roleService;

    @PostMapping("/create")
    public ApiResponse insertRole(Role roleVO) {
        try {
            if (roleService.insertRole(roleVO)) return ApiResponse.ok("创建成功");
            else return ApiResponse.failure("创建失败");
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.failure("创建失败");
        }
    }

    @PostMapping("/update")
    public ApiResponse updateRole(Role roleVO) {
        try {
//            System.out.println(roleVO);
            if (roleService.updateRole(roleVO)) return ApiResponse.ok("修改成功");
            else return ApiResponse.failure("修改失败");
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.failure("修改失败");
        }
    }

    @PostMapping("/delete/{id}")
    public ApiResponse deleteRole(@PathVariable String id) {
        try {
            if (roleService.deleteRole(Integer.parseInt(id))) return ApiResponse.ok("删除成功");
            else return ApiResponse.failure("删除失败");
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.failure("删除失败");
        }
    }

    @GetMapping("/list")
    public ApiResponse getRoleList() {
        try {
            return ApiResponse.ok("获取成功", roleService.getRoleList());
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.failure("获取失败");
        }
    }
    @GetMapping("/map")
    public ApiResponse getRoleIdMap(){
        try {return ApiResponse.ok(roleService.getRoleIdMap());
        }catch (Exception e){return ApiResponse.failure();}
    }
    @PostMapping("/grant")
    public ApiResponse grantRole(String user_id,String role_id){
        try{ if(roleService.grantRole(Integer.parseInt(user_id), Integer.parseInt(role_id))) return ApiResponse.ok();
        }catch (Exception e) {e.printStackTrace();}
        return ApiResponse.failure();
    }
    @PostMapping("/revoke")
    public ApiResponse revokeRole(String user_id,String role_id){
        System.out.println(user_id + " , " + role_id);
        try{ if(roleService.revokeRole(Integer.parseInt(user_id), Integer.parseInt(role_id))) return ApiResponse.ok();
        }catch (Exception e) {e.printStackTrace();}
        return ApiResponse.failure();
    }
}
